- Partition Array into Disjoint Intervals
Given an array A
, partition it into two (contiguous) subarrays left
and right
so that:
- Every element in
left
is less than or equal to every element inright
. left
andright
are non-empty.left
has the smallest possible size.
Return the length of left
after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
1 | Input: [5,0,3,8,6] |
Example 2:
1 | Input: [1,1,1,0,6,12] |
解法1
思路:从第一个位置开始遍历数组,maxVal记录属于前left的元素中的最大值,next记录从第一个位置到目前遍历到的位置中的最大值.当出现一个比当前记录的最大值更大的元素时,比较它与next,若它大于next,则更新next.当出现一个比maxVal小的元素时,更新left的右边界,即这个比maxVal也属于left,此时,更新maxVal = next.idx = i.
1 | class Solution { |